package org.example.oauth2.support;

import lombok.AllArgsConstructor;
import org.example.oauth2.config.JwtProperties;
import org.example.oauth2.service.CustomUserDetails;
import org.example.oauth2.utils.TokenUtil;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;


import java.util.HashMap;
import java.util.Map;

/**
 * jwt返回参数增强
 */
@AllArgsConstructor
public class TdiiJwtTokenEnhancer implements TokenEnhancer {

    private final JwtAccessTokenConverter jwtAccessTokenConverter;
    private final JwtProperties jwtProperties;

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        CustomUserDetails principal = (CustomUserDetails) authentication.getUserAuthentication().getPrincipal();

        //token参数增强
        Map<String, Object> info = new HashMap<>(16);
        info.put(TokenUtil.CLIENT_ID, TokenUtil.getClientIdFromHeader());
        info.put(TokenUtil.USER_ID, principal.getUserId().toString());
        info.put(TokenUtil.DEPT_ID, principal.getDeptId());
        info.put(TokenUtil.ROLE_ID, principal.getRoleId());
        info.put(TokenUtil.OAUTH_ID, principal.getOauthId());
        info.put(TokenUtil.ACCOUNT, principal.getAccount());
        info.put(TokenUtil.USER_NAME, principal.getUsername());
        info.put(TokenUtil.NICK_NAME, principal.getName());
        info.put(TokenUtil.REAL_NAME, principal.getRealName());
        info.put(TokenUtil.ROLE_NAME, principal.getRoleName());
        info.put(TokenUtil.AVATAR, principal.getAvatar());
        info.put(TokenUtil.LICENSE, TokenUtil.LICENSE_NAME);
        info.put("zkToken", principal.getZkToken());
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(info);

        //token状态设置
        if (jwtProperties.getState()) {
            OAuth2AccessToken oAuth2AccessToken = jwtAccessTokenConverter.enhance(accessToken, authentication);
            String tokenValue = oAuth2AccessToken.getValue();
            String userId = principal.getUserId().toString();
            //	JwtUtil.addAccessToken(userId, tokenValue, accessToken.getExpiresIn());
        }
        //获取复亚登录信息
        return accessToken;
    }
}
